package com.rtx.config.mybatis;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.rtx.api.annotation.RtxMybatisColumnName;
import com.rtx.api.annotation.RtxMybatisIgnore;

@SuppressWarnings("all")
public class SqlProvider {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	public String insert(Object entity) {
		StringBuffer insertsql = new StringBuffer();
		List<String> columns =new ArrayList<String>();
		List<String> values =new ArrayList<String>();
		
		try {
			Class clazz = entity.getClass();
			List<Field> fieldArray = new ArrayList<Field>();
			List list1 = Arrays.asList(clazz.getSuperclass().getDeclaredFields());
			List list2 = Arrays.asList(clazz.getDeclaredFields());
			fieldArray.addAll(list1);
			fieldArray.addAll(list2);
			
			String tableName = null;
			TableName tableNameHelp = (TableName) clazz.getDeclaredAnnotation(TableName.class);
			if(tableNameHelp == null) {
				TableName tableNameAnno  = (TableName) clazz.getSuperclass().getDeclaredAnnotation(TableName.class);
				tableName = tableNameAnno.value();
			}else {
				 tableName =tableNameHelp.value();
			}
			
			
			for(Field field:fieldArray) {
				String columnname = field.getName();
				RtxMybatisColumnName querycolumnnameAnno =field.getDeclaredAnnotation(RtxMybatisColumnName.class);
				if(!StringUtils.isEmpty(querycolumnnameAnno)&& !StringUtils.isEmpty(querycolumnnameAnno.name())) {
					columnname = querycolumnnameAnno.name();
				}
				
				field.setAccessible(true);
				Object value = field.get(entity);
				if(value == null || "null".equals(value)) {
					continue;
				}
				if(value instanceof List) {
					continue;
				}
				
				
				RtxMybatisIgnore ignore = field.getDeclaredAnnotation(RtxMybatisIgnore.class);
				if(null !=ignore) {
					continue; 
				}
				
				TableField tableField =  field.getDeclaredAnnotation(TableField.class);
				if(tableField != null) {
					if(!tableField.exist()) {
						continue;
					}
				}
				
				String valueStr = "";
				if(Date.class.equals(field.getType())) {
//					String dateStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(field.get(entity));
//					valueStr = "to_date('"+dateStr+"','yyyy-mm-dd hh:mi:ss')";
					valueStr ="'"+(field.get(entity)+"").replaceAll("'", "")+"'";
				}else {
					valueStr ="'"+(field.get(entity)+"").replaceAll("'", "")+"'";
				}
				
				if(!StringUtils.hasLength(valueStr) || "''".equals(valueStr)) {
					continue;
				}
				
//				columns.add(columnname);
				columns.add(columnname.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase());
				
				values.add(valueStr);
			}
			
			insertsql.append("insert into "+tableName);
			insertsql.append("("+columns.stream().collect(Collectors.joining(","))+")");
			insertsql.append(" values ");
			insertsql.append("("+values.stream().collect(Collectors.joining(","))+")");
			log.debug("{}插入sql:{}",tableName,insertsql.toString());
		} catch (Exception e) {
			log.error("生成insert语句异常",e);
		}

		return insertsql.toString();
	}
	
	public String upd(Object entity,Object where) {
		List<String> setcolumnsAndValues =new ArrayList<String>();
		
		StringBuffer updSql = new StringBuffer();
		
		List<String> wherecolumnsAndValue =new ArrayList<String>();
		
		try {
			//更新字段
			Class clazz = entity.getClass();
			List<Field> fieldArray = new ArrayList<Field>();
			List list1 = Arrays.asList(clazz.getSuperclass().getDeclaredFields());
			List list2 = Arrays.asList(clazz.getDeclaredFields());
			fieldArray.addAll(list1);
			fieldArray.addAll(list2);
			
			//查询条件
			List<Field> whereArray = new ArrayList<Field>();
			Class whereClass = where.getClass();
			List<Field> whereField = new ArrayList<Field>();
			List whereField1 = Arrays.asList(whereClass.getSuperclass().getDeclaredFields());
			List whereField2 = Arrays.asList(whereClass.getDeclaredFields());
			whereArray.addAll(whereField1);
			whereArray.addAll(whereField2);
			
			String tableName = null;
			TableName tableNameHelp = (TableName) clazz.getDeclaredAnnotation(TableName.class);
			if(tableNameHelp == null) {
				TableName tableNameAnno  = (TableName) clazz.getSuperclass().getDeclaredAnnotation(TableName.class);
				tableName = tableNameAnno.value();
			}else {
				 tableName =tableNameHelp.value();
			}
			
			
			for(Field field:fieldArray) {
				String columnname = field.getName();
				RtxMybatisColumnName querycolumnnameAnno =field.getDeclaredAnnotation(RtxMybatisColumnName.class);
				if(!StringUtils.isEmpty(querycolumnnameAnno)&& !StringUtils.isEmpty(querycolumnnameAnno.name())) {
					columnname = querycolumnnameAnno.name();
				}
				
				field.setAccessible(true);
				Object value = field.get(entity);
				if(value == null || "null".equals(value) || !StringUtils.hasLength(String.valueOf(false))) {
					continue;
				}
				if(value instanceof List) {
					continue;
				}
				
				RtxMybatisIgnore ignore = field.getDeclaredAnnotation(RtxMybatisIgnore.class);
				if(null !=ignore) {
					continue; 
				}
				
				TableField tableField =  field.getDeclaredAnnotation(TableField.class);
				if(tableField != null) {
					if(!tableField.exist()) {
						continue;
					}
				}
				
				String valueStr = "";
				if(Date.class.equals(field.getType())) {
					valueStr ="'"+(field.get(entity)+"").replaceAll("'", "")+"'";
				}else {
					valueStr ="'"+(field.get(entity)+"").replaceAll("'", "")+"'";
				}
				
				if(!StringUtils.hasLength(valueStr) || "''".equals(valueStr)) {
					continue;
				}
				
				String columnAndvalues  = columnname +"="+valueStr;
				setcolumnsAndValues.add(columnAndvalues);
			}
			
			for(Field field:whereArray) {
				String columnname = field.getName();
				RtxMybatisColumnName querycolumnnameAnno =field.getDeclaredAnnotation(RtxMybatisColumnName.class);
				if(!StringUtils.isEmpty(querycolumnnameAnno)&& !StringUtils.isEmpty(querycolumnnameAnno.name())) {
					columnname = querycolumnnameAnno.name();
				}
				
				field.setAccessible(true);
				Object value = field.get(where);
				if(value == null) {
					continue;
				}
				if(value instanceof List) {
					continue;
				}
				
				RtxMybatisIgnore ignore = field.getDeclaredAnnotation(RtxMybatisIgnore.class);
				if(null !=ignore) {
					continue; 
				}
				
				TableField tableField =  field.getDeclaredAnnotation(TableField.class);
				if(tableField != null) {
					if(!tableField.exist()) {
						continue;
					}
				}
				
				String valueStr = "";
				if(Date.class.equals(field.getType())) {
					valueStr ="'"+(field.get(where)+"").replaceAll("'", "")+"'";
				}else {
					valueStr ="'"+(field.get(where)+"").replaceAll("'", "")+"'";
				}
				String columnAndvalues  = columnname +"="+valueStr;
				wherecolumnsAndValue.add(columnAndvalues);
			}
			
			updSql.append("update "+tableName +" set ");
			updSql.append(setcolumnsAndValues.stream().collect(Collectors.joining(",")) +" ");
			updSql.append(" where ");
			updSql.append(wherecolumnsAndValue.stream().collect(Collectors.joining(" and ")));
			log.debug("{}插入update:{}",tableName,updSql.toString());
		} catch (Exception e) {
			log.error("生成update语句异常",e);
		}

		return updSql.toString();
	}
}
